import re
from rest_framework.mixins import ListModelMixin, DestroyModelMixin, UpdateModelMixin, RetrieveModelMixin, \
    CreateModelMixin
from rest_framework.viewsets import GenericViewSet
from.models import Medicine
from .serializer2 import MedicineSerializer, DepartmentSerializer
from ending_framework_api.apps.leaveplatform.page import MyPagination
from rest_framework.filters import OrderingFilter
from .SelfFilter import MyFilter
# 导入第三方模块的过滤模块
from django_filters.rest_framework import DjangoFilterBackend
from user.SelfFilter import MedicineFilter, DepartFilter

from utils.common_response import APIResponse
from utils.common_logging import logger
from rest_framework.viewsets import ViewSet, GenericViewSet, ViewSetMixin
from rest_framework.decorators import action
from libs.send_tx_msg import GetCode

# 判断是否登录
from rest_framework.permissions import IsAuthenticated
from .models import *
from .serializer import *
from .serializer2 import *
import queue

from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin,CreateModelMixin,RetrieveModelMixin,DestroyModelMixin
from settings.dev import MODE_VERIFICATION_CODE, AUTHENTICATION_MODE
from rest_framework.mixins import ListModelMixin, UpdateModelMixin, DestroyModelMixin, CreateModelMixin, \
    RetrieveModelMixin
from django_filters.rest_framework import DjangoFilterBackend
from utils.common_page import CommonPagination



class UserLoginView(ViewSet):

    @action(methods=['POST'], detail=False)
    def login(self, request):
        print(request.data)
        user_info = UserSerializer(data=request.data)
        user_info.is_valid(raise_exception=True)
        # print(user_info)
        user = user_info.context.get('user')
        user_id = user_info.context.get('user_id')
        token = user_info.context.get('token')
        user_type = user_info.context.get('user_type')
        gender = user_info.context.get('gender')
        mobile = user_info.context.get('mobile')
        print(gender)
        return APIResponse(msg='登录成功',
                           user=user,
                           token=token,
                           gender=gender,
                           user_type=user_type,
                           mobile=mobile,
                           user_id=user_id)


q_doctor = queue.Queue()


class UserRegisterView(ViewSet):

    @action(methods=['GET'], detail=False)
    def reg_department(self, request):
        department_list = []
        departments_jobs = Department.objects.all()
        # {obj1,obj2}
        for obj in departments_jobs:
            department_list.append({'department_id': obj.id, 'department_label': obj.name})
        return APIResponse(departments_data_type=department_list)

    @action(methods=['GET'], detail=False)
    def get_mobile(self, request):
        try:

            mobile = request.query_params.get('mobile')
            print(mobile)
            Doctor.objects.get(mobile=mobile)
            return APIResponse(code=101, msg='手机号已经存在')
        except:
            return APIResponse(code=100, msg='手机号验证通过')

    @action(methods=['POST'], detail=False)
    def register(self, request):
        print('第一步', request.data)
        # 注册的时候第一种情况选的是管理员，直接走管理员序列化类，把信息存进User表，只存了姓名和密码和user_type
        if not request.data.get('doctor'):
            # 把前端拿到的数据data传入序列化类
            ser = AdminRegisterSerializer(data=request.data)
        else:
            # 注册的时候第二种情况选的是医生或者药管师，直接走注册序列化类，把信息存进User表，只存了姓名和密码和user_type
            # 把前端拿到的数据data传入序列化类
            ser = UserRegisterSerializer(data=request.data)
        # 在序列化类中校验，通过则下一步，否则报错
        ser.is_valid(raise_exception=True)
        # 触发序列化类create方法
        info = ser.save()
        username = ser.context.get('username')

        q_doctor.put(info)
        return APIResponse(msg=f'账号:{username}注册已提交,等待管理员激活')


class UserForgetView(ViewSet):

    ###############测试腾讯云发送短信接口##########
    @action(methods=['GET'], detail=False)
    def send_sms(self, request, *args, **kwargs):
        # 前端需要把要发送的手机号传入 在地址栏中
        mobile = request.query_params.get('mobile', None)
        code = GetCode.send_sms_by_mobile(mobile)  # 把code存起来，放到缓存中
        cache.set('send_sms_code_%s' % mobile, code)
        # 从缓存中区
        # cache.get('send_sms_code_%s'%mobile)
        if mobile and GetCode.send_sms_by_mobile(mobile):
            return APIResponse(msg='发送成功')
        raise APIException('发送短信出错')

    ##############判断用户信息是否正确接口################
    @action(methods=['POST'], detail=False)
    def user_forget(self, request):
        print(request.data)
        ser = UserForgetSerializer(data=request.data)
        if ser.is_valid():
            user = ser.context.get('user')
            #######验证通过，返回user给前端
            return APIResponse(code=100, msg='验证通过了，下次要牢记密码奥！', user=user)
        else:
            raise APIException('再试一次吧！')

    ##############比较修改密码两次输入的密码是否一样接口#########

    @action(methods=['POST'],detail=False)
    def check_pwd(self,request):
        print(request.data)

    @action(methods=['POST'], detail=False)
    def check_pwd(self, request):

        user = request.data.get('user')
        password = request.data.get('password')
        confirm_pwd = request.data.get('confirm_pwd')
        if password == confirm_pwd:
            user = User.objects.all().filter(username=user).first()
            user.set_password(password)
            user.save()
            return APIResponse(msg='密码修改成功啦！！')
        else:
            return APIResponse(code=101, mag='两次密码不一样！！！')

    ##################验证手机号码接口###################
    @action(methods=['POST'], detail=False)
    def check_mobile(self, request):
        mobile = request.data.get('mobile')
        if not re.match(r'^1[3-9][0-9]{9}$', str(mobile)):
            raise APIException('手机号码格式不正确')
        user = User.objects.all().filter(doctor__mobile=mobile).first()
        if not user:
            raise APIException('你没有注册该手机号')
        logger.error('%s手机号码验证通过' % mobile)
        return APIResponse(msg='手机号验证通过!')

    ###################获取模拟或者腾讯云验证码接口##########
    @action(methods=['POST'], detail=False)
    def code_cache(self, request):
        mobile = request.data.get('mobile')
        if not re.match(r'^1[3-9][0-9]{9}$', str(mobile)):
            raise APIException('手机号码格式不正确！！')
        if AUTHENTICATION_MODE == 'debug':
            code = MODE_VERIFICATION_CODE
        else:
            code = GetCode.send_sms_by_mobile(mobile)
        if not code:
            raise APIException('验证码获取失败！！！')
        cache.set('set_code_%s' % mobile, code)
        logger.error('%s的验证码%s已经存入缓存中!!!!' % (mobile, code))
        return APIResponse(code=100, msg='验证码已经存入缓存中！！！')


class HeadFileView(ViewSet):


    #################上传头像接口#######################
    @action(methods=['POST'],detail=False)
    def upload_head(self,request):
        user = request.data.get('user')
        file = request.FILES.get('file')
        #####通过前面存入的user字段来判断给哪个用户存入头像入库
        user_obj = User.objects.all().filter(username=user).first()
        user_obj.icon = file

        user_obj.save()
        icon = 'http://127.0.0.1:8000/media/' + str(user_obj.icon)

        return APIResponse(msg='头像上传成功',icon=icon)



########################药品列表展示页面###################################
# class MedicineListView(GenericViewSet,ListModelMixin,CreateModelMixin,DestroyModelMixin,RetrieveModelMixin):
#     queryset = Medicine.objects.all()
#     serializers =



class UpdatePassword(ViewSet):
    ##########################修改密码接口############################
    @action(methods=['POST'],detail=False)
    def update_pwd(self,request):
        ser = UpdatePasswordSerializer(data = request.data)
        ser.is_valid(raise_exception=True)
        return APIResponse(msg='修改成功')

###########################用户信息展示页面############################
class GetUserView(GenericViewSet, RetrieveModelMixin, ListModelMixin):
    queryset = Doctor.objects.all()
    serializer_class = GetUserSerializer




#########################诊断医生开药#########################
class MedicineTypeView(ListModelMixin,GenericViewSet):
    queryset = Medicine.objects.all()
    serializer_class = MedicineSer

    def list(self, request, *args, **kwargs):
        ser = self.get_serializer(instance=self.queryset,many=True)
        print(ser.data)
        medicine_type = []
        for i in ser.data:
            type = i.get('category')
            medicine_type.append(type)
        medicine = []
        for i in set(medicine_type):
            medicine_category = []
            for item in ser.data:
                if item in ser.data:
                    if item.get('category') == i:
                        medicine_category.append(item.get('name'))
            medicine.append({f'{i}':medicine_category})
        return APIResponse(data=medicine)




################################### 药品管理  ######################
from .serializer import MedicineSerializers

# http://127.0.0.1:8000/api/v1/user/yao/
class MedicinView(GenericViewSet, ListModelMixin, UpdateModelMixin, DestroyModelMixin, CreateModelMixin,
                  RetrieveModelMixin):
    queryset = Medicine.objects.all().order_by('id')
    serializer_class = MedicineSerializers
    # 导入分页模块
    pagination_class = MyPagination
    # 导入排序
    # 排序模块使用 和 过滤功能
    filter_backends = [OrderingFilter, DjangoFilterBackend]  # 排序类
    # 配合一个类属性,按哪些字段可以排序
    # http://127.0.0.1:8000/api/v1/zhouge/?ordering=price  按价格由低到高升序排列
    # http://127.0.0.1:8000/api/v1/zhouge/?ordering=-price  按价格由高到低降序排列
    # http://127.0.0.1:8000/api/v1/zhouge/?ordering=id,  按ID号由低到到升序排列
    # http://127.0.0.1:8000/api/v1/zhouge/?ordering=-id,  按ID号由高到低降序排列
    # http://127.0.0.1:8000/api/v1/zhouge/?ordering=-price,-id
    # http://127.0.0.1:8000/api/v1/user/yao/?ordering=orders&size=2&page=2
    # 先按价格倒序排，价格一样，再按id倒叙排
    # ordering_fields = ['price', 'id']
    ordering_fields = ['id']

    # 使用过滤功能
    # filter_backends = [DjangoFilterBackend]
    # 按照名字和职务过滤
    filterset_fields = ['name']

# 查询所有的科室名称
class DepartmentView(GenericViewSet, ListModelMixin):
    queryset = Department.objects.all()
    serializer_class = DepartmentSerializerss

# 对科室表进行增删改查
# http://127.0.0.1:8000/api/v1/user/ke/
class DepartView(GenericViewSet, ListModelMixin, UpdateModelMixin, CreateModelMixin, DestroyModelMixin):
    queryset = Department.objects.all()
    serializer_class = DepartSerializer
    pagination_class = MyPagination
    filter_backends = [OrderingFilter, MyFilter]
    ordering_fields = ['id', ]  # 排序字段


# 搜索接口
# # 搜索接口 http://127.0.0.1:8000/api/v1/user/medsearch/
from rest_framework.viewsets import ViewSetMixin
from rest_framework.generics import ListAPIView
class MedicineSearchView(ViewSetMixin, ListAPIView):
    queryset = Medicine.objects.all()
    serializer_class = MedicineSerializer
    filter_backends = [MedicineFilter, ]


from .serializer import GetMedicineSerializer
###########  药房开单
# from rest_framework.mixins import RetrieveModelMixin
# 药房开单， 查询药品是否上架的名字，价格，数量
# # 药品开单  http://127.0.0.1:8000/api/v1/user/get_medicine/
class GetMedicineView(GenericViewSet, ListModelMixin, RetrieveModelMixin):
    queryset = Medicine.objects.all()
    serializer_class = GetMedicineSerializer

###################获取科室信息##########



class DepartmentInfoView(GenericViewSet, ListModelMixin, UpdateModelMixin, CreateModelMixin, DestroyModelMixin,RetrieveModelMixin):
    queryset = Department.objects.all().order_by('id')
    serializer_class = DepartmentSerializer
    pagination_class = CommonPagination
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ('name', 'depart_type')

    # filter_fields = ['name', 'depart_type']
    # search_fields = ['name', 'depart_type']
    # ordering_fields = ('id')
